<?php

class UserController extends St_Controller_Action {

    public function indexAction() {
        if (!$this->acl->isAllow("view_user")) {
            $this->_redirect("access/deny");
        }
        $sorting = $this->_getParam("sorting", false);
        $type = $this->_getParam("type", false);
        if ($sorting == '') {
            $type = ' DESC';
            $sortby = "SchoolID" . $type;
        } else {
            switch ($sorting) {
                case 'username':
                    $sortby = "UserName" . $type;
                    break;
                case 'groupID':
                    $sortby = "GroupID" . $type;
                    break;
                case 'email':
                    $sortby = "Email" . $type;
                    break;
                case 'createddate':
                    $sortby = "CreatedDate" . $type;
                    break;
                case 'school':
                    $sortby = "SchoolID" . $type;
                    break;
                case 'active':
                    $sortby = "IsActive" . $type;
                    break;
                default:
                    $sortby = "UserID" . $type;
            }
        }
        $this->view->isSuperAdmin = $this->isSuperAdmin(); // is supper admin
        $currentuser = $this->_getCurrentUser();

        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        $this->view->schoolObj = $datas;
        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $datas = $userObj->fetchAll();
        $this->view->datas = $datas;
        $type = $type == ' DESC' ? ' ASC' : ' DESC';
        $this->view->baselink = St_Registry::getConfig("base_url");
        $this->view->typesorting = $type;
        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();
        $school = $this->_getParam("school", false);
        if ($school != '') {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->joinLeft(array('g' => 'st_group'), 'g.GroupID = u.GroupID', array('GroupName' => 'GroupName'))
                    ->where("SchoolID = '$school'")
                    ->order($sortby)
            ;
        } else {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->joinLeft(array('g' => 'st_group'), 'g.GroupID = u.GroupID', array('GroupName' => 'GroupName'))
                    ->order($sortby)
            ;
        }
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        $db = St_Registry::getDB();
        $perpage = $db->query("SELECT keyword, value  from setting where keyword='default_table_row_page'");
        $perpage = $perpage->fetchColumn(1);
        $paginator->setItemCountPerPage($perpage);
        $paginator->setPageRange(5);
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);
    }

    public function deleteAction() {
        if (!$this->acl->isAllow("delete_user")) {
            $this->_forward("deny", "access");
            return;
        }

        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $uid = $this->_getParam("uid", false);

        $currentControllerName = St_Registry::getControllerName();
        if ($uid == 1) {
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        } else {
            $userObj->delete($userObj->getAdapter()->quoteInto("UserID = ?", $uid));
            $user = $this->_getCurrentUser();
            $this->logger->log($user['UserName'] . " deletes UserID =" . $uid);
        }
        //redirect to other action
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function activeAction() {

        if (!$this->acl->isAllow("active_user")) {
            $this->_forward("deny", "access");
            return;
        }
        Zend_Loader::loadClass("St_User");
        $userObj = new St_User ();
        $uid = $this->_getParam("uid", false);
        $status = $this->_getParam("currentstatus", "nostatus");

        $currentControllerName = St_Registry::getControllerName();
        if ($uid == 1 || $status == "nostatus") {
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        } else {

            $newStatus = ($status == "0") ? "1" : "0";

            $userObj->update(array('IsActive' => $newStatus), $userObj->getAdapter()->quoteInto("UserID = ?", $uid));
            $user = $this->_getCurrentUser();
            if ($newStatus == 1)
                $this->logger->log($user['UserName'] . " actives UserID =" . $uid);
            else
                $this->logger->log($user['UserName'] . " deactives UserID =" . $uid);
        }
        //redirect to other action
        $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
    }

    public function addAction() {

        if (!$this->acl->isAllow("add_user")) {
            $this->_forward("deny", "access");
            return;
        }
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $data = $this->_getParam("data", false);
        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        ;
        $this->view->schoolObj = $datas;
        if (($this->_getSuperAdminGroupID() == $data['GroupID']) && (!$this->isSuperAdmin())) {
            $canAdd = false;
        }

        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();

            if (($data['Password'] == "") || ($data['Password'] != $data['RetypePassword']) || (($data['UserName'] == ""))) {
                $canAdd = false;
            }

            unset($data['RetypePassword']);
            $data['Password'] = md5($data['Password']);
            $data['CreatedDate'] = time();
            $data['LastUpdated'] = time();
            if ($data['GroupID'] == 1) {
                $data['SchoolID'] = NULL;
            }
            if ($canAdd) {
                $result = $userObj->insert($data);
            }

            if ($result && $canAdd) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " adds a new user: " . $data['UserName']);
                $this->view->msg = "Add new user successfully";
            } else {
                $this->view->msg = "Can't add user";
            }
            $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
        }

        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll()->toArray();
        if (!$this->isSuperAdmin()) {
            $groupList = $groupObj->fetchAll("GroupID <> '{$this->_getSuperAdminGroupID()}'")->toArray();
        }
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
    }

    public function editAction() {
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/layouts/default/libs/JQuery/jquery.md5.js');
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $uid = $this->_getParam("uid", false);
        $user = $this->_getCurrentUser();
        if (!$uid) {
            $this->view->UserID = $user['UserID'];
            $this->_redirect("user/edit/uid/" . $user['UserID']);
        } else {
            if (!$this->acl->isAllow("edit_user") && $user['UserID'] != $uid) {
                $this->_forward("deny", "access");
                return;
            }
        }
        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        ;
        $this->view->schoolObj = $datas;
        $this->view->dataId = $uid;
        Zend_Loader::loadClass("St_User");
        $siteObj = new St_User();

        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'st_user'))
                ->joinLeft(array('g' => 'st_group'), 'g.GroupID = u.GroupID', array('GroupName' => 'GroupName'))
                ->where("UserID = '$uid'");
        $arrayRow = $db->fetchRow($select);

        if ($arrayRow) {
            $this->view->data = $arrayRow;
        }

        $data = $this->_getParam("data", false);

        if (($this->_getSuperAdminGroupID() == $data['GroupID']) && (!$this->isSuperAdmin())) {
            $canAdd = false;
        }

        if ($data) {

            if ($data['UserName'] == "") {
                $canAdd = false;
            }

            if (($data['Password'] != "" || $data['RetypePassword'] != "") && ($data['Password'] != $data['RetypePassword'])) {
                $canAdd = false;
            }

            if ($data['Password'] != "") {
                unset($data['RetypePassword']);
                $data['Password'] = md5($data['Password']);
            } else {
                unset($data['RetypePassword']);
                unset($data['Password']);
            }
            if ($data['GroupID'] == 1) {
                $data['SchoolID'] = NULL;
            }
            if ($canAdd) {
                $data['LastUpdated'] = time();
                $result = $siteObj->update($data, "UserID = '$uid'");
            }

            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " edits UserID=" . $uid);
                $this->view->msg = "Update user successfully";
            } else {
                $this->view->msg = "Can't update user";
            }
            $this->view->data = $data;
            if ($uid == $user['UserID']) {
                
            } else {
                $this->_redirect("{$currentControllerName}/index/page/{$this->_getParam("page", 1)}");
            }
        }

        // get list of group
        Zend_Loader::loadClass("St_Group");
        $groupObj = new St_Group();
        $groupList = $groupObj->fetchAll()->toArray();
        if (!$this->isSuperAdmin()) {
            $groupList = $groupObj->fetchAll("GroupID <> '{$this->_getSuperAdminGroupID()}'")->toArray();
        }
        $groupList = array_reverse($groupList);
        $this->view->groupList = $groupList;

        $this->view->isSuperAdmin = $this->isSuperAdmin();
    }

    public function accountingsettingsAction() {
        $currentControllerName = St_Registry::getControllerName();
        $db = St_Registry::getDB();
        $data = $this->_getParam("data", false);
        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();
            if (!empty($data['UserID'])) {
                if ($userObj->update($data, "UserID = {$data['UserID']}")) {
                    $message = array(
                        'status' => 'success',
                        'message' => 'Save successful'
                    );
                } else {
                    $message = array(
                        'status' => 'error',
                        'message' => 'Save unsuccessful'
                    );
                }
                St_Registry::sendMessage(json_encode($message));
                die;
            }
        }
        $UserID = '';
        if ($this->isSuperAdmin()) {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->where("GroupID != 1");
            $user_list = $db->fetchAll($select);
        } else {
            $user = $this->_getCurrentUser();
            $UserID = $user['UserID'];
        }

        $canAdd = true;
        $result = false;
        $arrayRow = '';
        if ($UserID) {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->where("UserID = '$UserID'");
            $arrayRow = $db->fetchRow($select);
        }
        $baseUrl = St_Registry::getConfig("base_url");

        $this->view->result = $arrayRow;
        $this->view->baseUrl = $baseUrl;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
        $this->view->user_list = $user_list;
        $this->view->user = $user;
    }

    public function getaccountingsettingsinfoAction() {
        $db = St_Registry::getDB();
        $UserID = $this->_getParam("UserID", false);
        $select = $db->select()
                ->from(array('u' => 'st_user'))
                ->where("UserID = '$UserID'");
        $arrayRow = $db->fetchRow($select);
        echo "{$arrayRow['Currency']}|**|{$arrayRow['VATObligated']}|**|{$arrayRow['VATPercentage']}|**|{$arrayRow['PaymentTerms']}|**|";
        die;
    }

    public function externalaccesssettingAction() {
        $currentControllerName = St_Registry::getControllerName();
        $db = St_Registry::getDB();
        $data = $this->_getParam("data", false);
        if ($data) {
            Zend_Loader::loadClass("St_User");
            $userObj = new St_User ();
            if (!empty($data['UserID'])) {
                if ($userObj->update($data, "UserID = {$data['UserID']}")) {
                    $message = array(
                        'status' => 'success',
                        'message' => 'Save successful'
                    );
                } else {
                    $message = array(
                        'status' => 'error',
                        'message' => 'Save unsuccessful'
                    );
                }
                St_Registry::sendMessage(json_encode($message));
                die;
            }
        }
        $UserID = '';
        if ($this->isSuperAdmin()) {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->where("GroupID != 1");
            $user_list = $db->fetchAll($select);
        } else {
            $user = $this->_getCurrentUser();
            $UserID = $user['UserID'];
        }

        $canAdd = true;
        $result = false;
        $arrayRow = '';
        if (empty($UserID)) {
            $UserID = $this->_getParam("UserID", false);
        }
        $getInfo = $this->_getParam("getInfo", false);
        if ($UserID) {
            $select = $db->select()
                    ->from(array('u' => 'st_user'))
                    ->where("UserID = '$UserID'");
            $arrayRow = $db->fetchRow($select);
            if ($getInfo) {
                echo "{$arrayRow['ExternalBrowserTitle']}|**|{$arrayRow['ExternalPageText']}|**|{$arrayRow['ExternalReportText']}";
                die;
            }
        }
        $baseUrl = St_Registry::getConfig("base_url");

        $this->view->result = $arrayRow;
        $this->view->baseUrl = $baseUrl;
        $this->view->isSuperAdmin = $this->isSuperAdmin();
        $this->view->user_list = $user_list;
        $this->view->user = $user;
    }

    public function registerAction() {
        $postCaptcha = $this->_getParam("captcha", false);
        $uploadDir = BASE_DIR . '/uploads/captcha';
        $baseUrl = St_Registry::getConfig("base_url");
        $captcha = new Zend_Form_Element_Captcha(
                        'captcha', // This is the name of the input field  
                        array(
                            'captcha' => array(
                                'captcha' => 'Image',
                                // Length of the word...  
                                'wordLen' => 8,
                                // Captcha timeout, 5 mins  
                                'timeout' => 300,
                                'font' => BASE_DIR . '\font\TFPironv2.otf',
                                // Where to put the image  
                                'imgDir' => $uploadDir,
                                // URL to the images  
                                // This was bogus, here's how it should be... Sorry again :S  
                                'imgUrl' => $baseUrl . 'uploads/captcha/',
                                'DotNoiseLevel' => '4',
                            ),
                            'class' =>'required'
                        )
        );
        Zend_Loader::loadClass('Zend_Gdata_AuthSub');
        $youtubeAuthenticateUri = Zend_Gdata_AuthSub::getAuthSubTokenUri(
                        St_Registry::getBaseUrl('user/register'), 'http://gdata.youtube.com', 0, 1);
        $this->view->youtubeAuthenticateUri = $youtubeAuthenticateUri;
        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'category'))
                ->order('categoryTitle');
        $categories = $db->fetchAll($select);
        $this->view->categories = $categories;
        $this->view->GroupID = $this->_getParam("GroupID", false);

        $canAdd = true;
        $result = false;
        $data = $this->_getParam("data", false);
        if (($this->_getSuperAdminGroupID() == $data['GroupID']) && (!$this->isSuperAdmin())) {
            $canAdd = false;
        }
        
        if (isset($_GET['token'])) {
            $session_token = Zend_Gdata_AuthSub::getAuthSubSessionToken($_GET['token']);
            $_SESSION['ytUserToken'] = $session_token;
            $httpClient = Zend_Gdata_AuthSub::getHttpClient($session_token);
            $yt = new Zend_Gdata_YouTube($httpClient, null, null, null);
            $yt->setMajorProtocolVersion(2);
            $userProfile = $yt->getUserProfile('default');
            
            $contactsFeed = $yt->getContactFeed($userProfile->getUsername());
            $count = 1;
//            echo $contactsFeed->title->text . "<br/>";
            foreach ($contactsFeed as $contactsEntry) {
                echo 'Entry # ' . $count . "<br/>";
                echo 'Contact: ' . $contactsEntry->title->text . "<br/>";
                foreach ($contactsEntry->category as $category) {
                    if ($category->scheme == 'http://schemas.google.com/g/2005#kind') {
                    $type = $category->term;
                    }
                }
                echo "\tType: " . $type . "<br/>";

                echo "<br/>";
                $count++;
            }


//            $serializeData = array(
//                'username'  => $userProfile->getUsername()->text,
//                'picture_url'  => $userProfile->getThumbnail()->getUrl(),
//                'about'  => $userProfile->getAboutMe(),
//                'age'  => $userProfile->getAge()->text,
//                'gender'  => $userProfile->getGender()->text,
//                'relationship'  => $userProfile->getRelationship(),
//                'hometown'  => $userProfile->getHometown(),
//                'location'  => $userProfile->getLocation()->text,
//                'hobbie'  => $userProfile->getHobbies(),
//                'book'  => $userProfile->getBooks(),
//                'movie'  => $userProfile->getMovies(),
//                'music'  => $userProfile->getMusic(),
//                'occupation'  => $userProfile->getOccupation(),
//                'company'  => $userProfile->getCompany(),
//                'school'  => $userProfile->getSchool(),
//                'memeberSince'  => $userProfile->getPublished()->text,
//            );
//            var_dump($serializeData);
        }
        $this->view->captcha = $captcha;
        if ($data) {
            if ($captcha->isValid($postCaptcha, $_POST)) {
                Zend_Loader::loadClass("UserModel");
                $userObj = new UserModel();
                $user = array();
                $user['UserName'] = $data['email'];
                $user['Password'] = $data['password'];
                $data['password'] = md5($data['password']);
                $data['createdDate'] = date('Y-m-d H:i:s', time());
                
                if ($userObj->checkExist('email', $data['email'])) {
                    $message = array(
                        'status' => 'error',
                        'message' => 'Email is already in used'
                    );
                    St_Registry::sendMessage(json_encode($message));
                    $canAdd = false;
                }

                if ($canAdd) {
                    $result = $userObj->insert($data);
                    $UserID = $db->lastInsertId();
                    if ($result) {
                        Zend_Loader::loadClass("St_Auth_Adapter");
                        $authAdapter = new St_Auth_Adapter ( );
                        
                        $authAdapter->setUserInfo($user['UserName'], $user['Password']);

                        $result = $this->auth->authenticate($authAdapter);
                        if ($result->isValid()) {
                            $_SESSION['CURRENT_USER'] = $this->_getCurrentUser();
                            echo 'true|*|' . $UserID; 
                            die;
                        }  else{
                            $message = array(
                                'status' => 'error',
                                'message' => 'Register failed please try again'
                            );
                            St_Registry::sendMessage(json_encode($message));

                        }                 
                        
                    } else {
                        echo 'false';
                    }
                } else {
                    echo 'false';
                }
            }
        }

        
    }

    public function registercategoryAction() {
        $this->_helper->layout()->disableLayout();
        $categoriesID = $this->_getParam("categoryID", false);
        $isReceiveEmail = $this->_getParam("receiveEmail", false);
        $UserID = $this->_getParam("UserID", false);
        if ($isReceiveEmail) {
            Zend_Loader::loadClass("UserModel");
            $userObj = new UserModel();
            $data = array('isReceiveEmail' => 1);
            $userObj->update($data, "UserID = $UserID");
        }
        if (count($categoriesID) > 0 && is_array($categoriesID) && $UserID) {
            Zend_Loader::loadClass("UserCategoryModel");
            $UserCategoryObj = new UserCategoryModel();
            $i = 0;
            foreach ($categoriesID as $v) {
                if ($i == 10)
                    break;
                $data = array(
                    'categoryID' => $v,
                    'UserID' => $UserID
                );
                $UserCategoryObj->insert($data);
                $i++;
            }
        }
        $this->_redirect("user/profile");
    }

    public function profileAction() {
        if (!$this->auth->hasIdentity() && (St_Registry::getActionName() != "logout") && (St_Registry::getActionName() != "deny")) {
            $this->_redirect("access/deny");
        }
    }
    
    public function sponsorprofileAction() {
        if (!$this->auth->hasIdentity() && (St_Registry::getActionName() != "logout") && (St_Registry::getActionName() != "deny")) {
            $this->_redirect("access/deny");
        }
    }

}

